<template>
    <div class='approval'>
      <el-card class="box-card" style="margin-top: 110px;">
        <div class='title'>
          {{$t('achievements.title1')}}
        </div>
        <div class='menu-search'> 
            <div class='menu-title'>
              <!-- 类型 -->
              <div class='searchItem'>
                <span>{{$t('approvalDetail.type')}}</span>
                <el-select v-model='listQuery.type' size='small'>
                  <el-option
                  v-for='item in typeArr'
                  :key='item.value'
                  :label='item.label'
                  :value='item.value'>
                  </el-option>
                </el-select>
              </div>
              <!-- APP渠道 -->
              <div class='searchItem'>
                <span>{{$t('ElectricChannel.AppChannel')}}</span>
                <el-select v-model='listQuery.channel' size='small'>
                    <el-option
                    v-for='item in appChannel'
                    :key='item.channel'
                    :label='item.org_name'
                    :value='item.channel'>
                    </el-option>
                </el-select>
                </div>
            </div>
            <div class='menu-title-btn'>
                <button type='button' @click='search'>
                    {{$t('btn.query')}}
                </button>
                <button type='button' @click='reset'>
                    {{$t('btn.reset')}}
                </button>
            </div>
        </div>
      </el-card>
        <el-card class='box-card' style="margin-top: 10px;margin-bottom: 20px;">
          <div class='title'>
              {{$t('ElectricChannel.dataList')}}
          </div>
          <el-table
              v-loading="listLoading"
              ref='multipleTable'
              :data='tableData'
              tooltip-effect='dark'
              style='width: 100%; margin-top: 5px;'
              @selection-change='handleSelectionChange'
              border
              size='mini'>
              <el-table-column
                :label="$t('RiskManager.number')"
                header-align='center'
                align='center'
                width="60">
                <template slot-scope="scope">
                  <span>{{scope.row.index}}</span>
                </template>
              </el-table-column>
              <!-- 类型 -->
              <el-table-column
              header-align='center'
              align='center'
              prop='attr2'
              width="130"
              :label="$t('approvalDetail.type')">
              <template slot-scope="scope">
                <span v-if="scope.row.attr2=== '1'">{{$t('RiskManager.SingleChannel')}}</span>
                <span v-else-if="scope.row.attr2=== '2'">{{$t('RiskManager.OverallSituation')}}</span>
              </template>
              </el-table-column>
              <!-- 关键词 -->
              <el-table-column
              header-align='center'
              align='center'
              prop='itemCode'
              width="150"
              :label="$t('RiskManager.KeyWord')">
              </el-table-column>
              <!-- 阈值(最小值) -->
              <el-table-column
              header-align='center'
              align='center'
              prop='minParam'
              width="140"
              :label="$t('RiskManager.thresholdMin')">
              </el-table-column>
              <!-- 阈值(最大值) -->
              <el-table-column
              header-align='center'
              align='center'
              prop='maxParam'
              width="140"
              :label="$t('RiskManager.thresholdMax')">
              </el-table-column>
              <!-- 备注 -->
              <el-table-column
              header-align='center'
              align='center'
              prop='desc'
              width="300"
              :label="$t('user.remarks')">
              </el-table-column>
              <!-- 状态 -->
              <el-table-column
              header-align='center'
              align='center'
              prop='attr1'
              width="170"
              :label="$t('grouping.status')">
              <template slot-scope="scope">
                <el-radio-group v-model="scope.row.attr1" size="mini" @change.native="changeStatus(scope.row)">
                    <el-radio label="1" size="mini">{{$t('AppVersion.enable')}}</el-radio>
                    <el-radio label="2" size="mini">{{$t('RiskManager.suspend')}}</el-radio>
                </el-radio-group>
              </template>
              </el-table-column>
              <el-table-column 
                align="center" 
                :label="$t('user.operation')" 
                width="100" 
                fixed="right"> 
                    <template slot-scope="scope">
                        <el-button size="small" type="text" @click="handleUpdate(scope.row)">{{$t('btn.edit')}}
                        </el-button>
                    </template> 
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="listQuery.page"
            :page-sizes="[10, 30, 50]"
            :page-size="listQuery.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
          </div>
        </el-card>
        <el-dialog :title="$t('route.RuleManager')" :visible.sync="dialogFormVisible" :before-close = "closeDialog">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px">
                <el-form-item :label="$t('RiskManager.number')" prop="index">
                    <el-input size='small' v-model="form.index" disabled style="width: 92%;"></el-input>
                </el-form-item>
                <el-form-item :label="$t('approvalDetail.type')" prop="attr2">
                     <el-select v-model='form.attr2' size='small' disabled>
                        <el-option
                        v-for='item in typeArr'
                        :key='item.value'
                        :label='item.label'
                        :value='item.value'>
                        </el-option>
                        </el-select>
                </el-form-item>
                <el-form-item :label="$t('ElectricChannel.AppChannel')" prop="channel">
                     <el-select v-model='form.channel' size='small' disabled>
                      <el-option
                      v-for='item in appChannel'
                      :key='item.channel'
                      :label='item.org_name'
                      :value='item.channel'>
                      </el-option>
                      </el-select>
                </el-form-item>
                <el-form-item :label="$t('RiskManager.KeyWord')" prop="itemCode">
                    <el-input size='small' v-model="form.itemCode" style="width: 92%;" disabled></el-input>
                </el-form-item>
                <el-form-item :label="$t('RiskManager.threshold')" required v-if="isShow">
                    <el-col :span="9">
                        <el-form-item prop="minParam">
                            <el-input size='small' :placeholder="$t('RiskManager.inpThresholdMin')" v-model="form.minParam" style="width: 100%;" @keyup.native="thresholdMinFn"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2" style="text-align: center;">-</el-col>
                    <el-col :span="9">
                        <el-form-item prop="maxParam">
                            <el-input size='small' :placeholder="$t('RiskManager.inpThresholdMax')" v-model="form.maxParam" style="width: 100%;" @keyup.native="thresholdMaxFn"></el-input>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item :label="$t('user.remarks')" prop="desc">
                    <el-input type="textarea" :placeholder="$t('rule.toLength')" :maxlength="500" :autosize="{ minRows: 3, maxRows: 5}" v-model="form.desc" style="width: 92%;"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel('form')">{{$t('btn.cancel')}}</el-button>
                <el-button type="primary" @click="update('form')">{{$t('btn.confirm')}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getChannels } from "api/customQuery/index";
import {
  ruleManagePage,
  updateMinMax,
  updateMinMaxCache,
  updateStartEnd,
  updateStartEndCache
} from "api/RiskManager/RuleManager/index";
export default {
  data() {
    return {
      isShow: false,
      form: {
        index: undefined,
        attr2: undefined,
        channel: undefined,
        itemCode: undefined,
        minParam: undefined,
        maxParam: undefined,
        desc: undefined
      },
      rules: {
        minParam: [
          {
            required: true,
            message: this.$t("creditSupermarket.ruleMinAmount")
          }
        ],
        maxParam: [
          {
            required: true,
            message: this.$t("creditSupermarket.ruleMaxAmount")
          }
        ],
        desc: [
          {
            required: true,
            message: this.$t("RiskManager.ruleDesc")
          }
        ]
      },
      dialogFormVisible: false,
      listLoading: false,
      total: null,
      expDis: true,
      listQuery: {
        limit: 10,
        page: 1,
        channel: '',
        type: "1"
      },
      tableData: [],
      multipleSelection: [],
      typeArr: [
        {
          value: "1",
          label: this.$t("RiskManager.SingleChannel")
        },
        {
          value: "2",
          label: this.$t("RiskManager.OverallSituation")
        }
      ],
      appChannel: []
    };
  },
  computed: {
    ...mapGetters(["elements", "RulesManagerPage"])
  },
  created() {
    if (this.RulesManagerPage.has(this.$route.path)) {
      this.listQuery = this.RulesManagerPage.get(this.$route.path);
    }
    // 渠道下拉
    getChannels().then(res => {
      this.appChannel = res.data;
      this.listQuery.channel = this.appChannel[0].channel;
      this.getList();
    });
  },
  methods: {
    cancel(formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
    },
    // 阈值限制
    thresholdMinFn() {
      if (this.form.minParam > this.form.maxParam) {
        this.$message({
          showClose: true,
          type: "warning",
          message: this.$t("RiskManager.thresholdMinRule")
        });
      }
      let val = this.form.minParam;
      val = String(val).replace(/[^\.\d]/g, "");
      val = String(val).replace(".", "");
      this.form.minParam = Number(val);
    },
    thresholdMaxFn() {
      if (this.form.maxParam < this.form.minParam) {
        this.$message({
          showClose: true,
          type: "warning",
          message: this.$t("RiskManager.thresholdMaxRule")
        });
      }
      let val = this.form.maxParam;
      val = String(val).replace(/[^\.\d]/g, "");
      val = String(val).replace(".", "");
      this.form.maxParam = Number(val);
    },
    closeDialog(done) {
      done();
      this.$refs["form"].resetFields();
      this.getList();
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.form = Object.assign({}, row);
      this.dialogFormVisible = true;
      if (row.attr2 === '1') {
        this.isShow = true;
      } else if (row.attr2 === '2') {
        this.isShow = false;
      }
    },
    // 编辑保存按钮
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          if (this.form.minParam > this.form.maxParam) {
            this.$message({
              showClose: true,
              type: "warning",
              message: this.$t("creditSupermarket.rangeMin")
            });
          } else {
            this.$confirm(this.$t("loanDetail.cue1"), {
              confirmButtonText: this.$t("btn.confirm"),
              cancelButtonText: this.$t("btn.cancel"),
              type: "warning",
              center: true
            })
              .then(() => {
                let editObj = {};
                editObj.minParam = this.form.minParam;
                editObj.maxParam = this.form.maxParam;
                editObj.keyWord = this.form.itemCode;
                editObj.desc = this.form.desc;
                updateMinMax(editObj).then(res => {
                  if (res.status === 200) {
                    let obj = {};
                    obj.keyWord = this.form.itemCode;
                    updateMinMaxCache(obj).then(response => {
                      if (response.status === 200) {
                        this.dialogFormVisible = false;
                        this.getList();
                        this.$notify({
                          title: this.$t("user.success"),
                          message: this.$t("user.crtsuccess"),
                          type: "success",
                          duration: 2000
                        });
                      } else {
                        this.$message({
                          showClose: true,
                          type: "warning",
                          message: response.message
                        });
                      }
                    });
                  } else {
                    this.$message({
                      showClose: true,
                      type: "warning",
                      message: res.message
                    });
                  }
                });
              })
              .catch(() => {
                this.$message({
                  showClose: true,
                  type: "info",
                  message: this.$t("loanDetail.cue3")
                });
              });
          }
        } else {
          return false;
        }
      });
    },
    changeStatus(row) {
      let obj = {};
      obj.status = row.attr1;
      obj.channel = this.listQuery.channel;
      obj.keyWord = row.itemCode;
      updateStartEnd(obj).then(res => {
        if (res.status === 200) {
          let channelObj = {};
          channelObj.channel = row.channel;
          channelObj.keyWord = row.itemCode;
          updateStartEndCache(channelObj).then(response => {
            if (response.status === 200) {
              this.$message({
                showClose: true,
                type: "success",
                message: this.$t("approvalDispatch.opersuccess")
              });
              this.getList();
            } else {
              this.$message({
                showClose: true,
                type: "warning",
                message: response.message
              });
              this.getList();
            }
          });
        }
      });
    },
    getList() {
      this.listLoading = true;
      this.$store.dispatch("saveRulesManagerPage", {
        path: this.$route.path,
        listQuery: this.listQuery
      });
      ruleManagePage(this.listQuery).then(res => {
        res.data.rows.forEach((item, index) => {
          item.index =
            index + (this.listQuery.page - 1) * this.listQuery.limit + 1;
        });
        this.expDis = false;
        this.listLoading = false;
        this.tableData = res.data.rows;
        this.total = Number(res.data.total);
      });
    },
    //查询
    search() {
      this.listQuery.page = 1;
      this.getList();
    },
    //重置
    reset() {
      this.listQuery.limit = 10;
      this.listQuery.page = 1;
      this.listQuery.channel = this.appChannel[0].channel;
      this.listQuery.type = "1";
    },
    //选中的数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    }
  }
};
</script>

<style scoped lang='scss'>
.box-card {
  width: 95%;
  margin-left: 2.5%;
  margin-right: 2.5%;
}
.title {
  line-height: 30px;
  font-size: 16px;
  display: flex;
  align-items: center;
  font-weight: bold;
}
.title:before {
  display: block;
  content: "";
  width: 3px;
  height: 16px;
  background-color: #309afe;
}
.title:before {
  margin-right: 8px;
}
::before {
  box-sizing: inherit;
  -webkit-tap-highlight-color: transparent;
}
.menu-title {
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .searchItem {
    display: flex;
    align-items: center;
    padding: 10px 0;
    span {
      display: inline-block;
      width: 100px;
      text-align: right;
      font-size: 12px;
      color: #5f5f61;
      padding-right: 5px;
    }
    div:nth-child(2) {
      width: 150px;
    }
  }
  .searchItem-date {
    display: flex;
    align-items: center;
    padding: 10px 0;
    b {
      margin: 0 10px;
      font-weight: normal;
      font-size: 12px;
      color: #5f5f61;
    }
    div {
      width: 150px;
    }
  }
}
.menu-title-btn {
  padding: 10px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
    &:nth-child(2) {
      background: #ebf5ff;
      color: #20a0ff;
      border: 1px solid #abd5ff;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.menu-list {
  padding: 20px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
</style>